package com.clp.protocol.modbus_tcp.mb_frame;

import com.clp.protocol.modbus_tcp.definition.MbFrmType;
import com.clp.protocol.modbus_tcp.mb_frame.mb_body.ReqMbBody;
import com.clp.protocol.modbus_tcp.mb_frame.mb_head.MbHead;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.Objects;

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ReqMbFrm implements MbFrm {
    @Override
    public MbFrmType mbFrmType() {
        return MbFrmType.REQ;
    }

    private MbHead head;
    private ReqMbBody body;

    @Override
    public ReqMbFrm initBy(ByteBuf buf) {
        this.head = new MbHead().initBy(buf);
        this.body = new ReqMbBody().initBy(buf);
        return this;
    }

    @Override
    public boolean isValid() {
        if (head == null || !head.isValid()) return false;
        return body != null && body.isValid();
    }

    @Override
    public void writeTo(ByteBuf buf) {
        head.writeTo(buf);
        body.writeTo(buf);
    }

    @Override
    public String toString() {
        switch (PrintOption.option) {
            case PrintOption.DESCRIPTION:
                return "请求帧：" + head + ", " + body;
            case PrintOption.HEX_STRING:
                return toHexString();
        }
        return null;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ReqMbFrm reqMbFrm = (ReqMbFrm) o;
        return Objects.equals(head, reqMbFrm.head) && Objects.equals(body, reqMbFrm.body);
    }

    @Override
    public int hashCode() {
        return Objects.hash(head, body);
    }
}
